package com.shuwen.gcdj.service.sysDictionary;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.sysDictionary.request.*;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.common.api.CommonPage;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import com.shuwen.gcdj.service.BaseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典
 *
 * @author yangx
 */
@Service
@AllArgsConstructor
@Slf4j
public class SysDictionaryService extends BaseService<SysDictionaryMapper, SysDictionary> {
    private final SysDictionaryMapper sysDictionaryMapper;

    /**
     * 查询字典-分页
     *
     * @param page
     * @param req
     * @return
     */
    public IPage<SysDictionaryResp> getPage(Page<SysDictionary> page, @Param("bean") SysDictionaryReq req) {
        return sysDictionaryMapper.getPage(page, req);
    }

    /**
     * 查询字典子项-分页
     *
     * @param req
     * @return
     */
    public CommonResult<CommonPage<SysDictionaryResp>> getChildPage(SysDictionaryChildReq req) {
        Page<SysDictionaryResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<SysDictionaryResp> data = sysDictionaryMapper.getChildPage(page, req);
        List<SysDictionaryResp> res = data.getRecords();
        Page<SysDictionaryResp> resPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resPage.setRecords(res);
        return CommonResult.success(CommonPage.restPage(resPage));
    }


    /**
     * 查询字典-集合
     *
     * @param req
     * @return
     */
    public List<SysDictionaryResp> getList(SysDictionaryReq req) {
        return sysDictionaryMapper.getList(req);
    }


    /**
     * 查询字典-单条
     *
     * @param req
     * @return
     */
    public SysDictionaryResp getSingle(SysDictionaryReq req) {
        return sysDictionaryMapper.getSingle(req);
    }


    /**
     * 查询字典-父级集合
     *
     * @param req
     * @return
     */
    public List<SysDictionaryResp> getListParentCode(SysDictionaryReq req) {
        return sysDictionaryMapper.getListParentCode(req);
    }


    /**
     * 查询字典-子集分页
     *
     * @param page
     * @param req
     * @return
     */
    public IPage<SysDictionaryResp> getListChild(Page<SysDictionary> page, SysDictionaryReq req) {
        return sysDictionaryMapper.getListChild(page, req);
    }

    /**
     * 查询字典-子集分页
     *
     * @param parentCode 父级code
     * @return
     */
    public List<SysDictionaryResp> getChildByParentCode(String parentCode) {
        if (parentCode.isEmpty()) {
            return null;
        }
        SysDictionaryReq req = new SysDictionaryReq();
        req.setParentCode(parentCode);
        req.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        return sysDictionaryMapper.getList(req);
    }


    /**
     * 新增字典明细
     *
     * @param user 用户信息
     * @param req  添加参数
     * @return 添加成功后的主键Id
     */
    public CommonResult<String> addDetail(InitUserDto user, AddSysDictionaryReq req) {
        String result = "";
        //if (verifyCode(req.getCode(), req.getParentCode(),null)) return CommonResult.failed("编号已存在");
        SysDictionary entity = new SysDictionary();
        entity.setCode(req.getCode());
        entity.setName(req.getName());
        entity.setValue(req.getValue());
        entity.setParentCode(req.getParentCode());
        entity.setRemark(req.getRemark());
        entity.setState(req.getState());
        entity.setOperateObject(req.getOperateObject());
        entity.setIsShow(1);
        entity.setCreateId(user.getUserId());
        entity.setUpdateId(user.getUserId());
        Boolean response = this.save(entity);
        if (!response) {
            return CommonResult.failed("添加失败");
        }
        result = entity.getId();
        return CommonResult.success(result);
    }


    /**
     * 编辑字典明细
     *
     * @param user 用户信息
     * @param req  添加参数
     * @return 添加成功后的主键Id
     */
    public CommonResult<Boolean> updateDetail(InitUserDto user, UpdateSysDictionartReq req) {
        Boolean result = false;
        //if (verifyCode(req.getCode(), req.getParentCode(),req.getId())) return CommonResult.failed("编号已存在");
        SysDictionary entity = this.getById(req.id);
        if (entity == null) {
            return CommonResult.failed("未找到字典明细信息，请重试");
        }
        entity.setName(req.getName());
        entity.setState(req.getState());
        entity.setCode(req.getCode());
        entity.setOperateObject(req.getOperateObject());
        entity.setRemark(req.getRemark());
        entity.setUpdateId(user.getUserId());
        Integer response = sysDictionaryMapper.updateById(entity);
        if (response == 0) {
            return CommonResult.failed("编辑失败");
        }
        result = response > 0;
        return CommonResult.success(result);
    }


    /**
     * 批量删除字典明细
     *
     * @param user 用户信息
     * @param req  添加参数
     * @return 添加成功后的主键Id
     */
    public CommonResult<Boolean> batchDeleteDetail(InitUserDto user, DeleteSysdictionaryReq req) {
        Boolean result = false;
        if (CollectionUtil.isEmpty(req.getIds())) {
            return CommonResult.failed("请选择删除对象");
        }
//        List<SysDictionary> entitys = sysDictionaryMapper.getListByIds(req.getIds());
        List<SysDictionary> entitys = this.list(new LambdaQueryWrapper<SysDictionary>()
                .in(SysDictionary::getId,req.getIds())
        );
        for (SysDictionary e : entitys) {
            e.setIsDelete(1);
            e.setUpdateId(user.getUserId());
        }
        result = this.updateBatchById(entitys);
        return CommonResult.success(result);
    }

    /**
     * 验证编号是否重复
     *
     * @param code       输入编号
     * @param parentCode 父级编号
     * @return 存在：ture 不存在：false
     */
    private boolean verifyCode(String code, String parentCode, String id) {
        Boolean result = false;
        List<SysDictionary> resp = this.list(new LambdaQueryWrapper<SysDictionary>()
                .eq(SysDictionary::getParentCode, parentCode)
                .eq(SysDictionary::getCode, code)
                .eq(SysDictionary::getIsDelete, 0));
        result = resp.size() > 0;
        if(id!=null) {
            result = resp.stream().filter(x -> !x.getId().equals(id)).collect(Collectors.toList()).size() > 0;
        }
        return result;
    }
}
